<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input
          placeholder="借款客户"
          @keyup.enter.native="getData()"
          @clear="getData()"
          clearable
          v-model="params.customer_name"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <c-select
          placeholder="客户类型"
          clearable
          number-key
          :options="enumCustomerType"
          v-model="params['org_class.eq']"
          @change="getData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <select-date-cascader
          placeholder="放款时间"
          class="form-control-ml"
          v-model="pickDateLoad"
          @select="handleDateLoadChange"
        ></select-date-cascader>
      </el-form-item>
      <el-form-item>
        <select-date-cascader
          placeholder="到期时间"
          class="form-control-ml"
          v-model="pickDateLoadEnd"
          @select="handleDateLoadEndChange"
        ></select-date-cascader>
      </el-form-item>

      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button class="btn-long" type="primary" @click="projectRemove">批量解保</el-button>
      </el-form-item>

      <el-form-item class="float-right">
        <el-button
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportExcel('解保清单', multipleSelection)"
        >
          导出所选项目
        </el-button>
      </el-form-item>
    </el-form>

    <c-table
      border
      v-loading="loading"
      :columns="tableColumns"
      :data="tableData"
      row-key="customer_related_id"
      ref="multipleTable"
      @selection-change="handleSelectionChange"
    ></c-table>
    <div class="query-pagination">
      <div class="pl-3">
        <small class="text-muted">
          (已选择
          <span class="text-info">{{ selectLen }}</span>
          个项目)
        </small>
      </div>
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        :page-sizes="[15, 100, 200, 500, 1000]"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <project-view-dialog
      :visible.sync="viewVisible"
      :batch-no="attachNo"
      :query-id="queryId"
    ></project-view-dialog>

    <remove-batch
      :visible.sync="removeVisible"
      :form-data="multipleSelection"
      @success="handleSuccess"
    ></remove-batch>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  enumloanStatusStyle,
  enumCustomerType,
  dataAdapter,
  parseCascaderDate,
} from '@/bank/views/limit/index'

import hndTableMixin from '@/bank/views/business/limit/history/mixins'

import ProjectViewDialog from '@/bank/views/business/limit/history/ProjectViewDialog'
import SelectDateCascader from '@/components/select/SelectDateCascader'
import RemoveBatch from '@/bank/views/business/limit/history/postloan/components/RemoveBatch'
import { excelJsonExport, columnToAbc } from '@vimi/utils-tool'
export default {
  components: {
    ProjectViewDialog,
    SelectDateCascader,
    RemoveBatch,
  },
  mixins: [hndTableMixin],
  props: {
    isEnd: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      enumLoanbehStatus: {
        1: '在保',
        2: '解保审核中',
        4: '提前解保',
        5: '正常解保',
      },
      enumCustomerType,
      loading: false,
      params: {
        index: 1,
        size: 10,
        'load_beh_status.eq': '1',
        'review_approval.gte': 4,
        'review_approval.neq': 9,
        'is_replace.neq': 1,
        customer_name: '',
        'channel_type.eq': 0,
        'is_rural_dev.eq': 0,
      },
      order: {
        load_date: 'desc',
      },
      tableName: 'datum_one_county_industry',
      tableColumns: [
        {
          attrs: {
            label: '选择',
            type: 'selection',
            align: 'center',
            width: 55,
            reserveSelection: true,
            // selectable: row => row.editAble,
          },
        },
        {
          attrs: { label: '借款客户', prop: 'customer_name', minWidth: '120px' },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
          }),
        },
        {
          attrs: { label: '放款银行名称', prop: 'bankName', align: 'center' },
        },

        { attrs: { label: '客户类型', prop: 'org_class_name', align: 'center' } },
        { attrs: { label: '贷款金额(万元)', prop: 'warranty_amount', align: 'center' } },
        { attrs: { label: '借据号', prop: 'iou_no', align: 'center' } },
        { attrs: { label: '证件号', prop: 'customerNo', align: 'center' } },
        { attrs: { label: '放款日期', prop: 'loadDate', align: 'center', minWidth: '100px' } },
        { attrs: { label: '到期日期', prop: 'loadEndDate', align: 'center', minWidth: '100px' } },
        {
          attrs: { label: '项目状态', prop: 'postloanStatus', align: 'center' },
          process: (_, row) => ({ attrs: { class: `text-${row.postloanStatusStyle}` } }),
        },
        {
          attrs: { label: '操作', align: 'center', width: '200px' },
          operations: [{ name: '查看', event: this.handleView }],
        },
      ],
      pickDateLoad: [],
      pickDateLoadEnd: [],

      tableData: [],
      tableCount: 0,

      // 附件上传
      attachVisible: false,
      attachProjectData: {},

      viewVisible: false,
      attachNo: '',
      queryId: '',
      repayVisible: false,

      unVisible: false,
      relatedData: {},
      multipleSelection: [],

      removeVisible: false,
    }
  },
  computed: {
    ...mapGetters(['clientId', 'userId']),
    isSubmit() {
      return this.user.scopes.includes('indoneBI')
    },
    selectLen() {
      return this.multipleSelection.length
    },
  },
  watch: {},
  created() {
    // 可解保项目只能是当前银行
    // this.params['bank_id.eq'] = this.clientId
    if (this.isEnd) {
      this.params['load_end_date.lt'] = this.$utils.dateFormat(new Date(), 'yyyy-MM-dd')
    }
    this.getData()
  },
  mounted() {},
  methods: {
    handleSizeChange(val) {
      this.params.size = val
      this.getData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    projectRemove() {
      if (!this.multipleSelection.length) {
        return this.$message.warning('请先选择解保项目')
      }
      this.removeVisible = true
    },
    // getParams() {
    //   return this.isSubmit
    //     ? {
    //         ...this.normalParams,
    //         ...this.params,
    //       }
    //     : {
    //         'submit_person.eq': this.userId,
    //         ...this.params,
    //       }
    // },
    handleDateLoadEndChange(val = []) {
      const [start, end] = parseCascaderDate(val)
      this.params['load_end_date.gte'] = start
      this.params['load_end_date.lte'] = end
      this.getData()
    },
    handleDateLoadChange(val = []) {
      const [start, end] = parseCascaderDate(val)
      this.params['load_date.gte'] = start
      this.params['load_date.lte'] = end
      this.getData()
    },
    handleSuccess() {
      this.$emit('success', true)
      this.multipleSelection = []
      const $tableRef = this.$refs.multipleTable.$children[0]
      $tableRef.clearSelection()
      this.getData()
    },
    // getData(index = 1) {
    //   this.params.index = index
    //   this.loading = true
    //   this.$api
    //     .getData(this.$serviceName, this.tableName, this.getParams(), this.order)
    //     .then(res => {
    //       const data = (res && res.data) || {}
    //       this.tableData = (data.data || []).map(this.dataAdapter)
    //       this.tableCount = data.totalCount || 0
    //     })
    //     .finally(() => {
    //       this.loading = false
    //     })
    // },

    dataAdapter(item) {
      item = dataAdapter(item)
      item.unGuaDate = this.$utils.dateFormat(item.un_gua_date, 'yyyy-MM-dd') || '-'

      item.postloanStatus = this.enumLoanbehStatus[item.load_beh_status] || ''
      item.postloanStatusStyle = enumloanStatusStyle[item.load_beh_status] || ''
      item.bankName = item.claim_bank_name || item.bank_name
      item.customerNo = +item.customer_type === 1 ? item.register_no : item.lender_idcard
      return item
    },

    handleView(row = {}) {
      this.queryId = row.customer_related_id
      this.attachNo = row.un_gua_batch_id || ''
      this.viewVisible = true
    },
    async exportExcel(filename, exportData) {
      const exportTable = [
        { attrs: { label: '序号', prop: 'index', align: 'center' } },
        { attrs: { label: '放款银行名称', prop: 'bankName', align: 'center' } },
        { attrs: { label: '借款客户', prop: 'customer_name', minWidth: '120px' } },
        { attrs: { label: '借据号', prop: 'iou_no', align: 'center' } },
        { attrs: { label: '证件号', prop: 'customerNo', align: 'center' } },
        { attrs: { label: '解保金额(万元)', prop: 'warranty_amount', align: 'center' } },
        { attrs: { label: '放款日期', prop: 'loadDate', align: 'center', minWidth: '100px' } },
        { attrs: { label: '到期日期', prop: 'loadEndDate', align: 'center', minWidth: '100px' } },
      ]
      const header = {}
      const headerCellStyles = {}
      const borderNull = {
        top: false,
        bottom: false,
        left: false,
        right: false,
      }
      let data = []
      data = exportData.map((item, index) => {
        return {
          index: index + 1,
          ...this.dataAdapter(item),
        }
      })
      const rows = data.length + 4

      const columns = exportTable.map((item, i) => {
        const { prop, label } = item.attrs || {}
        header[prop] = label

        headerCellStyles[`${columnToAbc(i)}1`] = { border: borderNull }
        headerCellStyles[`${columnToAbc(i)}2`] = { border: borderNull }
        headerCellStyles[`${columnToAbc(i)}${rows}`] = {
          alignment: { horizontal: 'left' },
          border: borderNull,
        }
        return prop
      })

      const title1 = {
        index: '解保项目清单',
      }
      const title2 = {
        index: '  银行盖章：',
      }
      const title3 = {
        index: '说明：以上项目确认解保，贵公司不再承担担保责任。',
      }

      excelJsonExport({
        columns,
        data: [title1, title2, header, ...data, title3],
        filename,
        styles: {
          border: {
            left: { style: 'thin' },
            top: { style: 'thin' },
            right: { style: 'thin' },
            bottom: { style: 'thin' },
          },
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        merges: ['A1:H1', 'A2:H2', `A${rows}:H${rows}`],
        autoWidth: false,
        cellStyles: {
          ...headerCellStyles,
          A1: {
            alignment: { horizontal: 'center' },
            font: { sz: 18 },
            border: borderNull,
          },

          A2: {
            alignment: { horizontal: 'left' },
            border: borderNull,
          },
        },
      }).finally(() => {
        this.exportLoading = false
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
